package com.echo.im.client.status.data;

import com.echo.im.client.constant.Constant;
import com.echo.im.client.constant.RedisConstant;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author echo
 */
public class RedisDataServiceImpl implements DataService {

    private  RedisTemplate<String, Object> redisTemplate;

    public RedisDataServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Map<Integer, Integer> fetchTerminalServerIdMap(Long userId) {

        Map<Object, Object> rawEntries = redisTemplate.opsForHash().entries(getRedisHashKey(userId));
        // 将 String 类型的 key 转换为 Integer
        Map<Integer, Integer> entries = rawEntries.entrySet().stream()
                .collect(Collectors.toMap(
                        // 手动将 key 转换为 Integer
                        entry -> Integer.parseInt((String) entry.getKey()),
                        entry -> (Integer) entry.getValue()
                ));
        return entries.isEmpty() ? (Map<Integer, Integer>) Constant.NULL_MARKER : entries;
    }

    private String getRedisHashKey(Long userId) {
        return String.format("%s:%d", RedisConstant.IM_USER_STATUS_NAME, userId);
    }

}
